package nio.cp2_buffer;

import java.nio.CharBuffer;

public class BufferFillDrain {

    private static int index;
    private static String [] strings = {
            "A random string value",
            "The product of an infinite number of monkeys",
            "Hey hey we're the Monkees",
            "Opening act for the Monkees: Jimi Hendrix",
            "'Scuse me while I kiss this fly", // Sorry Jimi ;-)
            "Help Me! Help Me!",
    };

    public static void main(String[] args) {

        CharBuffer buffer = CharBuffer.allocate(100);

/*        while (fillBuffer(buffer)){
            buffer.flip();
            drainBuffer(buffer);
            buffer.clear();
        }*/

        char[] bigArray = new char[100];
        char[] wrapArray = new char[100];
        buffer.wrap(wrapArray);
        buffer.put(strings[1]);
        char[] array = buffer.array();
        for (char c : array) {
            System.out.print(c);
        }

        System.out.println(wrapArray[2]);
        System.out.println(buffer.position());
        buffer.put(bigArray,0,buffer.remaining());
        buffer.get(bigArray,0,buffer.remaining());

        System.out.println(buffer.position());

    }
    public static void drainBuffer(CharBuffer buffer){

        while (buffer.hasRemaining()){
            System.out.print(buffer.get());
        }
        System.out.println();
        System.out.println("drainBuffer position:" + buffer.position());
        System.out.println("drainBuffer limit:" + buffer.limit());

    }

    public static boolean fillBuffer(CharBuffer buffer){

        if (index >= strings.length) {
            return (false);
        }
        String string = strings [index++];
        for (int i = 0; i < string.length( ); i++) {
            buffer.put (string.charAt (i));
        }
        System.out.println("Fill position:" + buffer.position());
        System.out.println("Fill limit:" + buffer.limit());
        return true;
    }
}
